package modellayer;

import java.util.*;

/**
 * The Class PersonContainer.
 */
public class PersonContainer
{

	/** The instance. */
	private static PersonContainer instance;

	/** The persons. */
	private ArrayList<Person> persons;

	/**
	 * Instantiates a new person container.
	 */
	public PersonContainer()
	{
		persons = new ArrayList<Person>();
	}

	/**
	 * Gets the single instance of PersonContainer.
	 *
	 * @return instance of PersonContainer
	 */
	public static PersonContainer getInstance()
	{
		if(instance == null)
		{
			instance = new PersonContainer();
		}
		return instance;
	}

	/**
	 * Adds the person.
	 *
	 * @param p the person
	 */
	public void addPerson(Person p)
	{
		persons.add(p);
	}

	/**
	 * Find person.
	 *
	 * @param phone String
	 * @return the person
	 */
	public Person findPerson(String phone)
	{
		int i=0;
		boolean found = false;
		while (!found && i < persons.size()) 
		{       
			if (phone.equals(persons.get(i).getPhone()))
			{
				found = true;
			}
			else i++;
		}
		if (found)
		{
			return persons.get(i);
		}
		else 
			return null;
	}

	/**
	 * Delete person.
	 *
	 * @param phone the phone
	 * @return true, if successful
	 */
	public boolean deletePerson(String phone)
	{
		boolean successful = true;
		if(findPerson(phone)==null)
		{
			successful = false;
		}
		persons.remove(findPerson(phone));
		return successful;
	}

	public boolean editPerson(String currentPhone, String name, String address, String postal, String city, String phone)
	{
		boolean successful = false;
		Person p = findPerson(currentPhone);
		if(name.isEmpty() != true)
		{
			p.setName(name);
		}
		if(address.isEmpty() != true)
		{
			p.setAddress(address);
		}
		if(city.isEmpty() != true)
		{
			p.setCity(city);
		}
		if(postal.isEmpty() != true)
		{
			p.setPostal(postal);
		}
		if(phone.isEmpty() != true)
		{
			p.setPhone(phone);
		}
		if(p.getAddress().equals(address) && p.getCity().equals(city) && p.getName().equals(name) && p.getPhone().equals(phone) && p.getPostal().equals(postal))
		{
			successful = true;
		}
		return successful;
	}

}
